package cn.tedu.fy.pethome.security;

import cn.tedu.fy.pethome.mapper.AdminMapper;
import cn.tedu.fy.pethome.pojo.vo.AdminListItemsVO;
import cn.tedu.fy.pethome.pojo.vo.AdminLoginVO;
import cn.tedu.fy.pethome.web.DataEnable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component

public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public AdminDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AdminLoginVO admin = adminMapper.getByUserName(s);
        if(admin!=null){
            //准备要返回给manager的数据
            Long id = admin.getId();
            String username = admin.getUsername();
            String password = admin.getPassword();
            Integer enable = admin.getEnable();
            List<String> permissions = admin.getPermissions();
            List<SimpleGrantedAuthority> authorities =new ArrayList<>();
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
            AdminDetails adminDetails = new AdminDetails(
                    id,username,password,enable== DataEnable.ENABLE,authorities);
            return adminDetails;

        }
        return null;

    }
}
